package com.qfhd.soft.cjzcore.Core;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.NetworkInterface;
import java.net.SocketException;

public class CJDevice {
    public String imei;
    public String imsi;
    public String android_id;
    public String brand;
    public String model;
    public String mac;
    public String screen_size;
    public String os_version;
    public int os_version_code;

//    public boolean isInitize = false;

    private static CJDevice device;
    public static CJDevice getInstance() {
        if (device == null) {
            synchronized (CJDevice.class) {
                device = new CJDevice();
            }
        }

        return device;
    }

    public String getDeviceJson() {
        return device.toString();
    }

    @SuppressLint("MissingPermission")
    public void init(Context context) {

        //查看保存的设备信息
        String DeviceInfo = CJFile.getDeviceInfoFromFile(context);
        if(DeviceInfo != null){
//            Gson gson = new Gson();
//            device = gson.fromJson(DeviceInfo,CJDevice.class);
            device = StringToDevice(DeviceInfo);
            CJLogger.v("deviceInfo getter success");
            return;
        }

        try {
            mac = getMacAddress(context);
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            display.getMetrics(displayMetrics);
            screen_size = displayMetrics.widthPixels + "x" + displayMetrics.heightPixels;
            brand = Build.BRAND;
            model = Build.MODEL;
            android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            os_version = Build.VERSION.RELEASE;
            os_version_code = Build.VERSION.SDK_INT;
            try {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                imei = tm.getDeviceId();
                imsi = tm.getSubscriberId();
            } catch (Exception e) {
                CJLogger.v("init get imei imsi e:" + e.toString());
                imei = android_id + "1";
                imsi = android_id + "2";
            }

            //设备信息只会取一次，不然imei会不同（没有权限获取的imei值不一样），所以要保存设备信息
            boolean ret = CJFile.saveDeviceInfoToFile(context,getDeviceJson());
            if(ret) CJLogger.v("deviceInfo save success");
            else CJLogger.v("deviceInfo save failed");

        } catch (Exception e) {
            CJLogger.v("refreshDeviceInfo error:" + e.toString());
        }
    }

    private String getMacAddress(Context context) {
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

    private CJDevice StringToDevice(String deviceStr){
        CJDevice tmp = new CJDevice();
        try {
            JSONObject obj = new JSONObject(deviceStr);
            tmp.imei = CJJsonUtils.getValueFromKey_string(obj,"imei");
            tmp.imsi = CJJsonUtils.getValueFromKey_string(obj,"imsi");
            tmp.android_id = CJJsonUtils.getValueFromKey_string(obj,"android_id");
            tmp.brand = CJJsonUtils.getValueFromKey_string(obj,"brand");
            tmp.model = CJJsonUtils.getValueFromKey_string(obj,"model");
            tmp.mac = CJJsonUtils.getValueFromKey_string(obj,"mac");
            tmp.screen_size = CJJsonUtils.getValueFromKey_string(obj,"screen_size");
            tmp.os_version = CJJsonUtils.getValueFromKey_string(obj,"os_version");
            tmp.os_version_code = CJJsonUtils.getValueFromKey_int(obj,"os_version_code");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return tmp;
    }

    @NonNull
    @Override
    public String toString() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("imei",imei);
            obj.put("imsi",imsi);
            obj.put("android_id",android_id);
            obj.put("brand",brand);
            obj.put("model",model);
            obj.put("mac",mac);
            obj.put("screen_size",screen_size);
            obj.put("os_version",os_version);
            obj.put("os_version_code",os_version_code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj.toString();
    }
}
